import 'dart:math';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/foundation.dart';
import 'package:on_audio_query/on_audio_query.dart';
import '../models/song.dart';
import 'dart:convert';

class MusicScannerService {
  static final MusicScannerService _instance = MusicScannerService._internal();
  factory MusicScannerService() => _instance;
  MusicScannerService._internal();

  final OnAudioQuery _audioQuery = OnAudioQuery();
  List<Song> _allSongs = [];
  bool _isPermissionGranted = false;
  bool _isScanning = false;

  // 检查权限
  Future<bool> checkPermissions() async {
    if (kIsWeb) {
      print('MusicScanner: Web平台跳过权限检查');
      return true;
    }

    if (_isPermissionGranted) return true;

    try {
      if (Platform.isAndroid) {
        // 首先尝试使用 on_audio_query 的权限检查
        final hasPermission = await _audioQuery.permissionsStatus();
        if (!hasPermission) {
          final requestResult = await _audioQuery.permissionsRequest();
          _isPermissionGranted = requestResult;
          print('MusicScanner: on_audio_query 权限请求结果: $requestResult');
        } else {
          _isPermissionGranted = true;
          print('MusicScanner: on_audio_query 权限已授予');
        }

        // 如果 on_audio_query 权限失败，尝试传统权限
        if (!_isPermissionGranted) {
          final permissions = [
            Permission.storage,
            Permission.audio,
            Permission.mediaLibrary,
          ];

          Map<Permission, PermissionStatus> statuses = await permissions.request();
          
          _isPermissionGranted = statuses.values.every(
            (status) => status == PermissionStatus.granted
          );
          
          print('MusicScanner: 传统权限请求结果: $_isPermissionGranted');
          print('MusicScanner: 权限状态详情: $statuses');
        }
      } else if (Platform.isIOS) {
        // iOS 权限处理
        final permission = await Permission.mediaLibrary.request();
        _isPermissionGranted = permission == PermissionStatus.granted;
        print('MusicScanner: iOS 权限请求结果: $_isPermissionGranted');
      } else {
        // 其他平台默认授权
        _isPermissionGranted = true;
      }
      
      print('MusicScanner: 最终权限状态: $_isPermissionGranted');
      return _isPermissionGranted;
    } catch (e) {
      print('MusicScanner: 权限检查出错: $e');
      return false;
    }
  }

  // 自动扫描所有音乐文件
  Future<List<Song>> scanAllMusicFiles() async {
    if (_isScanning) {
      print('MusicScanner: 正在扫描中，请等待...');
      return _allSongs;
    }

    _isScanning = true;
    
    try {
      // Web平台返回空列表
      if (kIsWeb) {
        _allSongs = [];
        return _allSongs;
      }

      // 检查权限
      final hasPermission = await checkPermissions();
      if (!hasPermission) {
        print('MusicScanner: 没有权限，返回空列表');
        _allSongs = [];
        return _allSongs;
      }

      print('MusicScanner: 开始扫描设备音乐文件...');
      
      // 使用 on_audio_query 扫描音频文件
      final songModels = await _audioQuery.querySongs(
        sortType: null,
        orderType: OrderType.ASC_OR_SMALLER,
        uriType: UriType.EXTERNAL,
        ignoreCase: true,
      );

      print('MusicScanner: 找到 ${songModels.length} 首歌曲');

      if (songModels.isEmpty) {
        print('MusicScanner: 未找到任何音频文件');
        _allSongs = [];
        return _allSongs;
      }

      List<Song> songs = [];
      
      for (final songModel in songModels) {
        try {
          // 获取专辑封面
          String? albumArtPath;
          try {
            final albumArt = await _audioQuery.queryArtwork(
              songModel.id,
              ArtworkType.AUDIO,
              format: ArtworkFormat.JPEG,
              size: 200,
            );
            
            if (albumArt != null && albumArt.isNotEmpty) {
              // 将字节数据转换为base64编码的data URI
              final base64String = base64Encode(albumArt);
              albumArtPath = 'data:image/jpeg;base64,$base64String';
            }
          } catch (e) {
            print('MusicScanner: 获取歌曲 ${songModel.title} 的封面失败: $e');
          }

          // 创建Song对象，不过滤任何歌曲
          final song = Song.fromAudioQuery(songModel, albumArtPath);
          songs.add(song);
          
          print('MusicScanner: 添加歌曲: ${song.name} - ${song.artist} (${song.duration})');
        } catch (e) {
          print('MusicScanner: 处理歌曲失败: ${songModel.title}, 错误: $e');
        }
      }

      _allSongs = songs;
      print('MusicScanner: 成功扫描到 ${_allSongs.length} 首本地音乐');

      return _allSongs;
    } catch (e) {
      print('MusicScanner: 扫描音乐文件失败: $e');
      _allSongs = [];
    } finally {
      _isScanning = false;
    }

    return _allSongs;
  }

  // 获取所有音乐文件
  Future<List<Song>> getAllMusicFiles() async {
    if (_allSongs.isEmpty) {
      return await scanAllMusicFiles();
    }
    return _allSongs;
  }

  // 获取本地扫描的歌曲
  Future<List<Song>> getLocalSongs() async {
    return await getAllMusicFiles();
  }

  // 获取随机歌曲
  Future<List<Song>> getRandomSongs(int count) async {
    final allSongs = await getAllMusicFiles();
    if (allSongs.length <= count) {
      return allSongs;
    }

    final shuffled = List<Song>.from(allSongs)..shuffle();
    return shuffled.take(count).toList();
  }

  // 获取单首随机歌曲
  Future<Song?> getRandomSong() async {
    final allSongs = await getAllMusicFiles();
    if (allSongs.isEmpty) {
      return null;
    }

    final random = Random();
    return allSongs[random.nextInt(allSongs.length)];
  }

  // 根据名称和艺术家查找歌曲
  Future<Song?> findSongByNameAndArtist(String name, String artist) async {
    final allSongs = await getAllMusicFiles();
    try {
      return allSongs.firstWhere(
        (song) => song.name == name && song.artist == artist,
      );
    } catch (e) {
      return null;
    }
  }

  // 搜索歌曲
  Future<List<Song>> searchSongs(String query) async {
    if (query.isEmpty) return [];
    
    final allSongs = await getAllMusicFiles();
    final lowercaseQuery = query.toLowerCase();
    
    return allSongs.where((song) {
      return song.name.toLowerCase().contains(lowercaseQuery) ||
             song.artist.toLowerCase().contains(lowercaseQuery) ||
             song.album.toLowerCase().contains(lowercaseQuery);
    }).toList();
  }

  // 按专辑分组
  Future<Map<String, List<Song>>> getSongsByAlbum() async {
    final allSongs = await getAllMusicFiles();
    final Map<String, List<Song>> albumMap = {};
    
    for (final song in allSongs) {
      if (!albumMap.containsKey(song.album)) {
        albumMap[song.album] = [];
      }
      albumMap[song.album]!.add(song);
    }
    
    return albumMap;
  }

  // 按艺术家分组
  Future<Map<String, List<Song>>> getSongsByArtist() async {
    final allSongs = await getAllMusicFiles();
    final Map<String, List<Song>> artistMap = {};
    
    for (final song in allSongs) {
      if (!artistMap.containsKey(song.artist)) {
        artistMap[song.artist] = [];
      }
      artistMap[song.artist]!.add(song);
    }
    
    return artistMap;
  }

  // 刷新音乐库
  Future<void> refreshMusicLibrary() async {
    _allSongs.clear();
    await scanAllMusicFiles();
  }

  // 清理资源
  void dispose() {
    _allSongs.clear();
    _isPermissionGranted = false;
    _isScanning = false;
  }
} 